﻿using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using KeyAuthService.Services;

namespace KeyAuthService
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public ServiceProvider ServiceProvider { get; private set; }

        public App()
        {
            // 配置服务
            var services = new ServiceCollection();
            ConfigureServices(services);
            ServiceProvider = services.BuildServiceProvider();
        }

        /// <summary>
        /// 配置依赖注入服务
        /// </summary>
        private void ConfigureServices(IServiceCollection services)
        {
            // 添加日志服务
            services.AddLogging(builder =>
            {
                builder.AddDebug();
                builder.AddConsole();
                
                // 配置日志文件
                string logFolder = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    "KeyAuthService", "Logs");
                
                if (!Directory.Exists(logFolder))
                {
                    Directory.CreateDirectory(logFolder);
                }
                
                string logFile = Path.Combine(logFolder, $"keyauth_{DateTime.Now:yyyyMMdd}.log");
                builder.AddFile(logFile);
            });

            // 添加核心服务
            services.AddSingleton<KeyAuthCore>();
            services.AddSingleton<KeyStorageService>();
            services.AddSingleton<UIService>();
            services.AddSingleton<WebSocketServer>();
            services.AddSingleton<Services.KeyAuthService>();

            // 添加主窗口
            services.AddSingleton<MainWindow>();
        }

        /// <summary>
        /// 应用程序启动事件
        /// </summary>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // 显示主窗口
            var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }

        /// <summary>
        /// 应用程序退出事件
        /// </summary>
        protected override void OnExit(ExitEventArgs e)
        {
            // 释放服务提供者
            ServiceProvider.Dispose();
            
            base.OnExit(e);
        }
    }

    /// <summary>
    /// 日志文件扩展方法
    /// </summary>
    public static class FileLoggerExtensions
    {
        public static ILoggingBuilder AddFile(this ILoggingBuilder builder, string filePath)
        {
            builder.AddProvider(new FileLoggerProvider(filePath));
            return builder;
        }
    }

    /// <summary>
    /// 文件日志提供者
    /// </summary>
    public class FileLoggerProvider : ILoggerProvider
    {
        private readonly string _filePath;

        public FileLoggerProvider(string filePath)
        {
            _filePath = filePath;
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new FileLogger(_filePath);
        }

        public void Dispose()
        {
        }
    }

    /// <summary>
    /// 文件日志记录器
    /// </summary>
    public class FileLogger : ILogger
    {
        private readonly string _filePath;
        private readonly object _lock = new object();

        public FileLogger(string filePath)
        {
            _filePath = filePath;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return logLevel != LogLevel.None;
        }

        public IDisposable? BeginScope<TState>(TState state) where TState : notnull
        {
            return null;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            try
            {
                var message = formatter(state, exception);
                
                lock (_lock)
                {
                    File.AppendAllText(_filePath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{logLevel}] {message}{Environment.NewLine}");
                    
                    if (exception != null)
                    {
                        File.AppendAllText(_filePath, $"{exception}{Environment.NewLine}");
                    }
                }
            }
            catch
            {
                // 忽略日志写入错误
            }
        }
    }
}
